package com.example.demo.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.Util.Http;
import com.example.demo.config.ApiConstant;
import com.example.demo.config.jwt.JwtConfig;
import com.example.demo.entity.User;
import com.example.demo.entity.Userinfo;
import com.example.demo.mapper.UserMapper;
import com.example.demo.mapper.UserinfoMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Fyly
 * @since 2019-03-30
 */
@Api(value = "用户controller", tags = {"用户操作接口"})
@RestController
@RequestMapping("/User/")
public class UserController {

    @Autowired
    private UserMapper usermapper;

    @Autowired
    private UserinfoMapper userinfoMapper;

    @Resource
    private JwtConfig jwtConfig;

    /*
    *@Param
    * code: code
    * avatarUrl: 用户头像地址
    * nickName: 用户名
    * gender: 用户性别
    * city: 用户所在城市
    * province: 用户省份
    * */
    @ApiOperation(value = "登录接口")
    @ApiImplicitParams({
          @ApiImplicitParam(name = "code", value = "code", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "avatarUrl", value = "用户头像地址", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "nickName", value = "用户名", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "gender", value = "用户性别", required = false, dataType = "string", paramType = "query"),
    })
    @GetMapping("doLogin")
    public Map<String, Object> doLogin(@RequestParam("code") String code , @RequestParam("avatarUrl") String avatarUrl ,
                                       @RequestParam("nickName") String nickName , @RequestParam("gender") String gender ){

        //根据code获取openid
        JSONObject SessionKeyOpenid = getOpenid(code);
        String openid = SessionKeyOpenid.getString("openid");
        String sessionKey = SessionKeyOpenid.getString("session_key");

        //返回参数
        Map<String, Object> map = new HashMap<>();

        User user = usermapper.selectByOpenid(openid);

        if(user == null){

            System.out.println("用户不存在 重新添加用户");
            //保存用户登录数据
            User user1 = new User();
            user1.setOpenId(openid);
            user1.setSessionKey(sessionKey);
            user1.setRegTime(new Date());
            user1.setVisitTime(new Date());
            user1.setUserType("小程序");

            usermapper.insert(user1);
            //添加用户数据
            User user2 = usermapper.selectByOpenid(openid);

            Userinfo userinfo = new Userinfo();
            userinfo.setAvatarUrl(avatarUrl);
            userinfo.setNickName(nickName);
            userinfo.setGender(Integer.parseInt(gender));
            userinfo.setUserId(user2.getId());

            userinfoMapper.insert(userinfo);


            User tokenUser = new User();
            tokenUser.setOpenId(openid);
            tokenUser.setSessionKey(sessionKey);

            //JWT返回自定义登录态 Token
            String token = jwtConfig.createTokenByWxAccount(tokenUser);
            map.put("token",token);
            map.put("code",200);
        }else{
            //用户已经存在！
            System.out.println("用户openid已经存在");
            map.put("code",200);
        }

        return map;
    }

    /*
    * 获取openid
    * */
    public static JSONObject getOpenid(String code){



        JSONObject jsonObject =  null;

        try {
            //配置参数
            Map<String, Object> map = new HashMap<>();
            map.put("appid", ApiConstant.APIID);
            map.put("secret", ApiConstant.SECRET);
            map.put("js_code", code);
            map.put("grant_type", ApiConstant.GRANTTYPE);

            //发送请求
            Http http = new Http();
            String rs = http.sendGet(ApiConstant.WX_OPENIDURL, map, "utf_8");

            jsonObject = JSON.parseObject(rs);

            String sessionKey = jsonObject.get("session_key").toString();
            String openid = jsonObject.get("openid").toString();
            //输出一下
            System.out.println("openid=" + openid);

            return jsonObject;
        }catch (Exception e){
            e.printStackTrace();
        }

        return jsonObject;
    }
}

